<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Withdrawal");
$page_title=__("Withdrawal");
$content_title=__("Withdrawal");

$item_per_page=$vars["user_item_per_page"];

//#####WITHDRAWAL#####
$r_settings=get_settings('member_withdraw_min,max_withdraw_month');
$min_withdraw=$r_settings["member_withdraw_min"];
$max_wit_per_month=$r_settings["max_withdraw_month"];
$r_payment=array("b");
$r_payment_d=array("b"=>__("Bank"));
$r_bank_name=array("Hong Leong Bank", "HSBC", "Malayan Banking Berhad", "Oversea-Chinese Banking Corporation Limited", "Public Bank Berhad", "Standard Chartered PLC");
$r_bank_name_d=array("Hong Leong Bank"=>__("Hong Leong Bank"), "HSBC"=>__("HSBC"), "Malayan Banking Berhad"=>__("Malayan Banking Berhad"), "OCBC"=>__("Oversea-Chinese Banking Corporation Limited"), "Public Bank Berhad"=>__("Public Bank Berhad"), "Standard Chartered PLC"=>__("Standard Chartered PLC"));
$r_withdraw=array();
$r_withdraw_d=array();
for($i=1; $i<=500; $i++){	
	$amount = $i * 100;
	array_push($r_withdraw, $amount);
	$r_withdraw_d[$amount]="GBP".number_format($amount, 0);
}
$td_width=180;

/*##### FORM POST #####*/
if($_POST["__req"]){
 //##### CHECK POST DATA #####
 $errmsg=verify_form_data("member_withdraw", $post_s);
 if(!$errmsg){
  //check password
  if(!strlen($post_s["password"])){
   $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Password")))."<br />\n";
  }else{
   $enc_pass=explode(":", $r_user["ewallet_enc_password"]);
   if(md5($post_s["password"].$enc_pass[1]) != $enc_pass[0]){
    $errmsg.=__("You have entered an invalid AuthCode.")."<br />\n";
   }
  }
  //check min withdraw amount
  if($post_s["withdraw"]<$min_withdraw){
   $errmsg.=replace_tag(__("Minimum Withdrawal Amount: <%currency%><%x%>"), array("<%currency%>"=>$vars["currency"], "<%x%>"=>number_format($min_withdraw, 2)))."<br />\n";
  //check cash balance
  }elseif($post_s["withdraw"]>$r_user["ewallet"]){
   $errmsg.=replace_tag(__("You do not have sufficient <%title%>."), array("<%title%>"=>__($vars["ewallet_title"])))."<br />\n".replace_tag(__("<%title%> requested: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($post_s['withdraw'], 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($r_user['ewallet'], 2)))."<br />\n";
  //check max no. of withdrawal reach per month
  }else{
   $last_30_days = date('Y-m-d', ntime() - (30*86400))." 00:00:00";
   $this_month=@mysql_result(mysql_query($s="select count(*) from $db->member_withdraw where uid='$uid' and status!='cancelled' and cdate>='$last_30_days'"), 0) or 0;
   if($this_month >= $max_wit_per_month){
    $errmsg.=replace_tag(__("You have already requested <%x%> <%withdrawal%> in this month. You can only request for withdrawal again in the next month."), array("<%x%>"=>strval($this_month), "<%withdrawal%>"=>$this_month>1? __("withdrawals") : __("withdrawal")))."<br />\n";
   }
  }
 }
 if(!$errmsg){
  if($post_s["__confirm"]){
   $datetime=ndate($vars["system_date_format"]);
   //deduct e-wallet
   if(!mysql_query($sql="update $db->users set ewallet=ewallet-$post_d[withdraw] where id='$uid' limit 1")){
    $errmsg.=__("We have some error processing your withdrawal request.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
   }else{
    //create e-wallet record
    if(!mysql_query($ewr_sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$post_d[withdraw]', '".AddSlashes("Debited $vars[currency]".number_format($post_d['withdraw'], 2)." for withdrawal requested by you")."', '$datetime')")){
     $critical_error.="Error creating the member $vars[ewallet_title] record when member ID #$uid request a withdrawal. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
    }else{
		$new_eid = mysql_insert_id();
		$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
		if(!$last_bal){
			$last_bal = 0;
		}
		$last_bal -= $post_s['withdraw'];
		@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
	}
	
	//5% processing fees
    $withdrawal_amount = $post_d['withdraw'] * 0.95;
	    
    //create withdrawal record
    $sql="insert into $db->member_withdraw (uid, amount, withdraw_amount, payment_type, acc_name, acc_payee_name, acc_no, acc_swiftcode, acc_branch, remark, autowit, status, cdate)
    values ('$uid', '$post_d[withdraw]', '$withdrawal_amount', 'o', '".mysql_real_escape_string($post_d['acc_name'])."', '".mysql_real_escape_string($post_d['acc_payee_name'])."', '".mysql_real_escape_string($post_d['acc_no'])."', '".mysql_real_escape_string($post_d['acc_swiftcode'])."', '".mysql_real_escape_string($post_d['acc_branch'])."', '$post_d[_remark]', 'n', 'pending', '$datetime')";
    if(!mysql_query($sql)){
     $errmsg.=__("We have some error processing your withdrawal request.")." ".replace_tag(__("Your <%title%> account has been deducted <%x%>."), array("<%title%>"=>__($vars["ewallet_title"]), "<%x%>"=>number_format($post_s["withdraw"], 2)))." ".__("Please contact us.")."<br />\n".($vars["debug"]? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
     $critical_error.="Error creating the member withdrawal record when member ID #$uid request a withdrawal and this member's $vars[ewallet_title] account has been deducted ".number_format($post_s["withdraw"], 2).". Please manually record this withdrawal by executing SQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
    }else{
     $new_wid=mysql_insert_id();
    }
   }
   if(!$errmsg){
    $a_sub="$vars[title] - $vars[ewallet_title] Withdrawal by Member ID #$uid";
    $a_msg=
    "<p>Dear admin,</p>
    <p>A member ID #$uid has just requested an $vars[ewallet_title] withdrawal of $vars[currency] ".number_format($post_s["withdraw"], 2).", Withdraw ID: $new_wid.
    You can process this withdrawal from the $vars[title] Administrative Panel.</p>";
    email_admin($a_sub, $a_msg);
    $process_day="7";
    $msg=replace_tag(__("Your withdrawal has just been sent. Please allow up to <%x%> business <%day%> for your withdrawal to be processed."), array("<%x%>"=>"$process_day", "<%day%>"=>$process_day>1? __("days") : __("day")))."<br />\n";
    print format_member_page($inc_wallet_select."<h2>$page_title</h2>".format_msg($msg), $this_title, $content_title,$inc_jvscript);
   }
  }
 }

 if($critical_error){
  $a_sub="$vars[title] - Membership Withdrawal Failure for Member ID #$uid";
  $a_msg="
  <p>Dear admin,</p>
  <p>There was some error(s) while member ID #$uid requests for withdrawal. The error is as follow:</p>
  $critical_error";
  email_admin($a_sub, $a_msg, 'e');
 }

 if($msg){
  exit();
 }

 $errmsg=$errmsg? format_err($errmsg) : "";
}

$form_fields=array("acc_name"=>"", "acc_payee_name"=>"", "acc_no"=>"", "acc_swiftcode"=>"", "acc_branch"=>"", "withdraw"=>"100","payment"=>"b","_remark"=>"","password"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$posting? $default : $post_h[$field]);
}
$bank_name_select=build_select($r_bank_name, $r_bank_name_d, $dis["acc_name"], "acc_name", $inputbox_style);
$payment_select=build_select($r_payment, $r_payment_d, $dis["payment"], "payment", $inputbox_style);
$withdraw_select=build_select($r_withdraw, $r_withdraw_d, $dis["withdraw"], "withdraw", $inputbox_style);

if(!$errmsg && $post_s["__preview"]){
 $preview=true;
 foreach($dis as $field=>$value){
  $post_fields.="<input type='hidden' name='$field' value=\"$value\" />\n";
 }
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=withdraw_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });".(!$preview? "
 update_payment_type('$dis[payment]');" : "")."

function update_payment_type(type){
 j('tr[@id^=pt_]').hide();
 j('tr[@id=pt_'+type+']').show();
}
});

function form_back(){
 document.withdraw_form.__confirm.value='';
 document.withdraw_form.submit();
}
</script>";

$display_fields=array("acc_name","acc_payee_name","acc_no","acc_swiftcode","acc_branch","withdraw","_remark");
foreach($form_fields as $field=>$default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["member_withdraw"][$db_fieldname]);
  $readonly=$textarea=$password=false;
  $extra_display="";
  if($field=='withdraw'){
   $extra_display="<br />\n<span>".replace_tag(__("<%title%> Available: <%currency%><%x%>"), array("<%title%>"=>__($vars["ewallet_title"]), "<%currency%>"=>$vars["currency"], "<%x%>"=>number_format($r_user["ewallet"], 2)))."</span>";
  }
  if($field=='_remark'){
   $textarea=true;
  }
  if($field=='password'){
   $password=true;
  }
  $add_class="";
  $readonly_str=$readonly? "readonly='readonly' class='readonly'" : "";
  $add_class=$readonly? "readonly" : "";
  $inputbox_style2=$add_class? preg_replace('/^class=\'/', "class='$add_class ", $inputbox_style) : $inputbox_style;
  $form_inputfield[$db_fieldname]="
  <tr id='input_$db_fieldname'>
   <td width='$td_width'>".__($dbr[4]).__(":")."</td>
   <td>".($preview? $dis[$field] : ($textarea? "<textarea name='$field' rows='6' $inputbox_style2 $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='".($password? "password" : "text")."' name='$field' $inputbox_style2 value=\"".$dis[$field]."\" $readonly_str />")."$extra_display")."</td>
  </tr>";
 }
}

//payment type account info
$payment_bank_row=
"
<tr id='pt_b'>
 <td>".__("BP Balance").__(":")."</td>
 <td>$r_user[ewallet]</td>
</tr>";


//#####Preview
if($preview){
$withdrawal=
"<form name='withdraw_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='__confirm' value='1' />
$post_fields
<table class='pbt_table'>
 $form_inputfield[acc_name]
 $form_inputfield[acc_payee_name]
 $form_inputfield[acc_no]
 $form_inputfield[acc_swiftcode]
 $form_inputfield[acc_branch]
 $form_inputfield[withdraw]		 
 $form_inputfield[remark]
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value=\"".__("Back")."\" class='button' onclick=\"form_back();\" /> &nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".__("Confirm")."\" class='button' />
  </td>
 </tr>
</table>
</form>";
//#####Start / Edit
}else{
	$r_user=get_user_detail_by_id($uid);
	
		$withdrawal=($errmsg || $msg?
		"$errmsg $msg" : "")."
		<form name='withdraw_form' method='post' action='$this_file'>
		<input type='hidden' name='__req' value='1' />
		<input type='hidden' name='__preview' value='1' />
		<table class='pbt_table'>		 
		 <tr>
		  <td width='$td_witdh'>".__("Bank Name").__(":")."</td>
		  <td>".$bank_name_select."</td>
		 </tr>
		 $form_inputfield[acc_payee_name]
		 $form_inputfield[acc_no]
		 $form_inputfield[acc_swiftcode]
		 $form_inputfield[acc_branch]
		 <tr>
		  <td width='$td_witdh'>".__("Withdrawal Amount").__(":")." ".__("*")."</td>
		  <td>".$withdraw_select."<br />\n<span>".replace_tag(__("<%title%> Available: <%currency%><%x%>"), array("<%title%>"=>__($vars["ewallet_title"]), "<%currency%>"=>$vars["currency"], "<%x%>"=>number_format($r_user["ewallet"], 2)))."</span></td>
		 </tr> 
		 $form_inputfield[remark]
		 <tr>
		  <td>".__("AuthCode").__(":")."</td>
		  <td><input type='password' name='password' value=\"$dis[password]\" $inputbox_style /></td>
		 </tr>
		 <tr>
		  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>";
		  
		  if(date('d')=='21')
			$withdrawal.="<input type='submit' name='submit_btn' value=\"".__("Preview")."\" />";
		  else
		  	$withdrawal.="<b>".__("Withdrawal date will be on every month 21th!")."</b>";
		  
		  $withdrawal.="</td>
		 </tr>
		</table>
		</form>";
}

$content=$inc_wallet_select."<h2>$page_title</h2>$withdrawal";

print format_member_page($content, $this_title, $content_title, $css.$jvscript.$inc_jvscript);
?>